package org.omixed.flex;

import java.util.ArrayList;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

class ShellMain
{
	
	final static private Logger logger = Logger.getLogger("ShellMain");
	
	private static final String[] defaultServerValues = {
		"server",
		"/Users/buggy/bin/flex3/bin/fcsh",
		"53000" 
	};
	
	private static final String[] defaultClientValues = {
		"client",
		"mxmlc -output /mnt/us/home/buggy/code/OmixedFlasher/Schematographer/bin/SchematograqpherApplet.swf /mnt/us/home/buggy/code/OmixedFlasher/Schematographer/SchematographerApplet.mxml", 
		"53000",
		"localhost"
	};
	
	public static void main(String [ ] args) throws ShellException, IOException
	{
		PropertyConfigurator.configure("log4j.properties");
		
		if (args.length == 0)
		{
			throw new ShellException ("Must specifiy the if you want to start the server or client.");
		}
		String action = args[0];
		
		if (action.equals("server"))
		{
			startServer(args);
		}
		else if (action.equals("client"))
		{
			startClient(args);
		} else
		{
			throw new ShellException ("Unknown action: "+ action);
		}
	}
	
	
	private static void startServer(String [ ] args) throws IOException, ShellException
	{
		String fcshPath = getFromArray(1, args, defaultServerValues);
		String portString = getFromArray(2, args, defaultServerValues);
		
		logger.info("fcshPath: "+ fcshPath);
		logger.info("portString: "+ portString);
		
		
		int port = Integer.parseInt(portString);
		ShellServer inst = new ShellServer(fcshPath, port);
	}
	
	private static void startClient(String [ ] args) throws UnknownHostException, IOException, ShellException
	{
		String command = args[1];
		String portString = getFromArray(2, args, defaultServerValues);
		String addrString = getFromArray(3, args, defaultServerValues);
		
		logger.info("command: "+ command);
		logger.info("portString: "+ portString);
		logger.info("addrString: "+ addrString);
		
		int port = Integer.parseInt(portString);
		InetAddress addr = InetAddress.getByName(addrString);
		ShellClient client = new ShellClient(addr, port, command);
		String results = client.send();
		System.out.println(results);
	}
	
	private static String getFromArray(int index, String[] list,  String[] defaults)
	{
		int lastIndex = list.length -1;
		int defaultsLastIndex = defaults.length -1;
		if (index <= lastIndex)
		{
			return list[index];
		}
		if (index <= defaultsLastIndex)
		{
			return defaults[index];
		}
		return "";
	}
	
	
	
}